﻿/*function addTab(title, url,currentid,parentid,notclose){
	var id = parentid + "_" + currentid;
	var tabs = $('#tabs');
	if (tabs.tabs('exists', id)){
		tabs.tabs('select', id);//选中并刷新
		/*
		var currTab = $('#tabs').tabs('getSelected');
		var url = $(currTab.panel('options').content).attr('src');
		if(url != undefined && currTab.panel('options').title != 'Home') {
			$('#tabs').tabs('update',{
				tab:currTab,
				options:{
					content:createFrame(url)
				}
			})
		}
		
	} else {
		var option = {
			title:title,
			id:id,
			content:'',
			closable:!notclose
		};
		tabs.tabs('add',option);
		var tab = tabs.tabs('getTab',id);
		var fr = document.createElement("IFRAME");
		fr.frameBorder = 0;
		fr.border = 0;
		fr.style.width = "100%";
		fr.style.height = "100%";		
		tab.append(fr);
		fr.src = url;
		option.frame = fr;
	}
}
*/
// 对页面进行渲染 g：页面定义 b：是否初始加载内容
function jsPageRender(g, b,d) {	
    if (g.formDefine) {
		if(b) g.autosearch = function() {jsPageSearch(g,d);};
		formRender(g);
    }
	else jsPageSearch(g,d);
}
function jsPageSearch(g, data) {
	if(!g.grid) gridRender(g);
	g.grid.clearAll();
	 if (g.grid.usePager == false && g.gridDefine.url && g.gridDefine.urlType) {
        g.grid.LoadData4NoPage();
    }else if (data){
	    if (data instanceof Array && data.length > 0) g.grid.loadData(data);
	}else
	     g.grid.LoadRemoteData(1);
}

function jsPageCopy(sourceG,targetG){
	if(sourceG.grid.checkedAll) {
		targetG.gridDefine.params = function() { return sourceG.grid._getParams(); };
		targetG.gridDefine.url = sourceG.gridDefine.url;
		targetG.gridDefine.urlType = sourceG.gridDefine.urlType;
	} else {
		targetG.gridDefine.canCheckAll = false;
		targetG.gridDefine.usePager = false;
	}
	gridRender(targetG);
	if(sourceG.grid.checkedAll) {
		targetG.grid.checkedAll = true;
		targetG.grid.uncheckedRows = sourceG.grid.uncheckedRows;
		targetG.grid.LoadRemoteData(1);
	} else {
		targetG.grid.loadData(sourceG.grid.getSelectedRows());
		targetG.grid.target.datagrid('selectAll');
	}
}
// 使用form的下面接口
// form.getParams()
// form.getParamsStr()
// form.target
// form.getDisplayType()
// form.id
function gridRender(g) {
	var gd = g.gridDefine;
	var id = g.gridId || gd.gridId || 'tableid';
	g.grid = {
	    // 表格id
	    id: id,
	    // 对象
	    target: $('#' + id),
	    usePager: (gd.usePager != false),
	    // 取得选中的行
	    getSelectedRows: function () {
	        var that = this;
	        if (that.checkedAll) return [];
	        return that.target.datagrid('getChecked');
	    },
	    // 取得未选中的行
	    getUnSelectedRows: function () {
	        var that = this;
	        if (!that.checkedAll) return [];
	        return that.uncheckedRows || [];
	    },
	    clearAll: function () {
	        var that = this;
	        that.target.datagrid('clearSelections');
	        that.uncheckedRows = [];
	    },
	    getData: function () {
	        var that = this;
	        return that.target.datagrid('getRows');
	    },
	    // 加载数据
	    loadData: function (data, length) {
	        var that = this;
	        that.target.datagrid('loadData', { "total": length || data.length, "rows": data });
	    },
	    // 参数取得
	    _getParams: function () {
	        var params;
	        // 表单获取查询条件
	        if (g.form) params = g.form.getParams();
	        if (typeof gd.params == "function") params = gd.params(params);
	        //扩展参数
	        if (typeof gd.extparams == "function") params = gd.extparams(params);
	        if (typeof params == "object") return $.toJSON(params);
	        return params || "{}";
	    },
	    // 加载完毕的信息设置
	    _loaded: function (msg) {
	        // 查询条件
	        var that = this;
	    
//	        if (g.form) {
//	            var title = "";
//	            if (g.form) title = g.form.getParamsStr();
//	            if (!title || title == "") title = "全部";
//	            if (title) that.target.datagrid('setTitle', { title: '已选条件:' + title, click: g.grid.titleClick });
//	            if (g.grid.titleClick) g.form.target.hide();
//	        }
	        $("#" + that.id + 'pinfo').html(msg);
	    },
	    // 加载远程数据
	    LoadRemoteData: function (page, pageSize) {
	        var that = this;
	        if (!(gd.url || gd.urlType)) return;
	        // 重新回到第一页
	        var pg = that.target.datagrid("getPager");
	        if (pg && pg.length > 0 && !pageSize) {
	            $(pg).pagination('refresh', { pageNumber: 1 });
	            pageSize = $(pg).pagination('options').pageSize;
	        }
	        // 开始时间
	        var _ajaxBeforeTime = new Date();
	        var ajaxObj = {
	            urlType: gd.urlType,
	            url: gd.url,
	            model: that._getParams(),
	            Page: { 'CurrentPage': page, 'PageSize': pageSize },
	            ColOrder: { 'ColName': that.sortName || '', 'Sort': that.sortOrder == 'desc' ? 1 : 0 },
	            success: function (data, Page, DataDifferTime) {
	                that.loadData(data, Page.Records);
	                var msg = " all time:" + (new Date() - _ajaxBeforeTime) + " data time:" + DataDifferTime;
	                that._loaded(msg);
	                if (gd.dataComplete)
	                    gd.dataComplete(data);
	            },
	            failure: function (msg) {
	                alert(msg);
	                that._loaded(msg);
	            }
	        }
	        $.ajaxHandler(ajaxObj);
	    },
	    //不带分页
	    LoadData4NoPage: function () {
	        var that = this;
	        var ajaxObj = {
	            urlType: gd.urlType,
	            url: gd.url,
	            model: that._getParams(),
	            success: function (data) {
	                that.loadData(data);
	                if (gd.dataComplete)
	                    gd.dataComplete(data);
	            },
	            failure: function (msg) {
	                alert(msg);
	            }
	        }
	        $.ajaxHandler(ajaxObj);
	    },
	    clearAll: function () {
	        var that = this;
	        that.target.datagrid('uncheckAll');
	        that.target.datagrid('clearSelections');
	        that.target.datagrid('clearChecked');
	    },
	    checkAll: function (btn) {
	        var that = this;
	        if (!that.checkedAll) {
	            $(btn).find(".l-btn-text").removeClass("icon-check").addClass("icon-uncheck").html('cancle all page');
	            that.target.datagrid('checkAll');
	        } else {
	            $(btn).find(".l-btn-text").removeClass("icon-uncheck").addClass("icon-check").html('select all page');
	            that.clearAll();
	        }
	        that.checkedAll = !(that.checkedAll || false);
	    },
	    disabledTool: function (toolbarBtn) {
	        var that = this;
	        that.target.datagrid('toolbarDisabled', toolbarBtn.text);
	    },
	    enableTool: function (toolbarBtn) {
	        var that = this;
	        that.target.datagrid('toolbarEnabled', toolbarBtn.text);
	    }
	};

	var gridOpt = {
	    // 表格定义转换
	    convert: function (g) {
	        var gd = g.gridDefine;
	        var that = this;
	        var opt = {};
	        opt.striped = true; //设置为true,将交替显示行背景。
	        opt.nowrap = true; //设置为true,当数据长度超出列宽时将会自动截取。
	        opt.frozenColumns = []; //冻结列
	        opt.columns = []; //常规列
	        opt.toolbar = [];
	        opt.autoRowHeight = gd.autoRowHeight; //是否自动行高
	        opt.fit = true;

	        //固定高度处理
	        if (gd.height) { opt.height = gd.height; opt.fit = false; }
	        if (gd.width) { opt.width = gd.width; opt.fit = false; }
	        //表明该列是一个唯一列
	        if (gd.rowKey) opt.idField = gd.rowKey;
	        var frozenColumns = [];
	        var columns = [];
	        var columns2 = []; //用于复杂列处理
	        var isComplexCol = false;
	        // 选择框处理
	        if (gd.checkbox) frozenColumns.push({ field: 'ck', checkbox: true });
	        // 列处理
	        var col;
	        for (var p = 0; p < gd.columns.length; p++) {
	            col = that._2column(gd.columns[p]);
	            if (!g.grid.sortName && (gd.columns[p].sort == 'desc' || gd.columns[p].sort == 'asc')) {
	                g.grid.sortName = col.field;
	                g.grid.sortOrder = gd.columns[p].sort;
	            }

	            if (gd.columns[p].frozen) frozenColumns.push(col);
	            else {
	                // 如果是复杂列头
	                if (col.childColumns) {
	                    $.merge(columns2, $.map(col.childColumns, function (n) { return that._2column(n); }));
	                    col.colspan = col.childColumns.length;
	                    if (!isComplexCol) {
	                        isComplexCol = true;
	                        // 对之前的进行处理
	                        for (var i in columns) columns[i].rowspan = 2;
	                    }
	                } else {
	                    if (isComplexCol) col.rowspan = 2;
	                }
	                columns.push(col);
	            }
	        }
	        opt.frozenColumns.push(frozenColumns);
	        opt.columns.push(columns);
	        if (columns2.length > 0) opt.columns.push(columns2);

	        //列头是否显示右建
	        if (!gd.ContextMenu) {
	            opt.onHeaderContextMenu = function (e, field) {
	                e.preventDefault();
	                if (!g.grid.colmenu) that._createColumnMenu(g, columns);
	                g.grid.colmenu.menu('show', { left: e.pageX, top: e.pageY });
	            }
	        }
	        // 排序处理
	        if (gd.remoteSort === false) {
	            opt.remoteSort = false;
	        } else {
	            opt.onSortColumn = function (sort, order) {
	                g.grid.sortName = sort;
	                g.grid.sortOrder = order;
	                g.grid.LoadRemoteData(1);
	            }
	        }

	        // 是否允许checkall
	        if (gd.canCheckAll) {
	            // 数据加载完成后处理
	            opt.onLoadSuccess = function (data) {
	                // 如果选中所有
	                if (g.grid.checkedAll) {
	                    var key = opt.idField;
	                    g.grid.target.datagrid('checkAll');
	                    //重新绑定未选择的列表
	                    $(g.grid.uncheckedRows).each(function (i, urow) {
	                        $(data.rows).each(function (index, row) {
	                            if (urow[key] == row[key]) {
	                                g.grid.target.datagrid('uncheckRow', index);
	                                return;
	                            }
	                        })
	                    })
	                }
	            }
	            // 如果选中所有页,对未选择的项选中时
	            opt.onCheck = function (index, row) {
	                if (g.grid.checkedAll) {
	                    var key = opt.idField;
	                    if (!g.grid.uncheckedRows) g.grid.uncheckedRows = [];
	                    for (var i = 0; i < g.grid.uncheckedRows.length; i++) {
	                        if (row[key] == g.grid.uncheckedRows[i][key]) {
	                            g.grid.uncheckedRows.splice(i, 1);
	                            return;
	                        }
	                    }
	                }
	            }
	            // 如果选中所有页,对选择的项不选中时
	            opt.onUncheck = function (index, row) {
	                if (g.grid.checkedAll) {
	                    var key = opt.idField;
	                    if (!g.grid.uncheckedRows) g.grid.uncheckedRows = [];
	                    for (var i = 0; i < g.grid.uncheckedRows.length; i++) {
	                        if (g.grid.uncheckedRows[i][key] == row[key])
	                            return;
	                    }
	                    g.grid.uncheckedRows.push(row);
	                }
	            }
	        }
	       /*
            opt.title = '';// gd.title; // 标题
	        if (g.form) {
	            var flag = g.form.getDisplayType();
	            // =1,就是不浮动,2:就是浮动,3就是嵌入表格按钮里面
	            if (flag == '2') {
	                opt.title = opt.title || " "; // 标题
	                g.form.target.addClass('myformfloat');
	                g.grid.titleClick = function () { g.form.target.toggle(); };
	            }
	        }
            */
	        // 设置为true将显示行数
	        opt.rownumbers = (gd.rownumbers != false);
	        opt.pagination = (gd.usePager != false); //设置true将在数据表格底部显示分页工具栏

	        if (gd.toolbar) {
	            $.each(gd.toolbar.items, function (i, n) {
	                if (i == 0 && gd.canCheckAll) {
	                    opt.toolbar.push($.extend(that._2toolbar(toolbarBtn.checkall), { grid: g.grid }));
	                    opt.toolbar.push('-');
	                }
	                opt.toolbar.push($.extend(that._2toolbar(n), { grid: g.grid }));
	                opt.toolbar.push('-');
	            });
	        }
	        return opt;
	    },
	    // 表格头menu创建
	    _createColumnMenu: function (g, fields) {
	        var that = this;
	        g.grid.colmenu = $('<div/>').appendTo('body');
	        g.grid.colmenu.menu({
	            onClick: function (item) {
	                if (item.iconCls == 'icon-ok') {
	                    g.grid.target.datagrid('hideColumn', item.name);
	                    g.grid.colmenu.menu('setIcon', {
	                        target: item.target,
	                        iconCls: 'icon-empty'
	                    });
	                } else {
	                    g.grid.target.datagrid('showColumn', item.name);
	                    g.grid.colmenu.menu('setIcon', {
	                        target: item.target,
	                        iconCls: 'icon-ok'
	                    });
	                }
	            }
	        });
	        for (var i = 0; i < fields.length; i++) {
	            var field = fields[i];
	            g.grid.colmenu.menu('appendItem', {
	                text: field.title,
	                name: field.field,
	                iconCls: 'icon-ok'
	            });
	        }
	    },
	    _2toolbar: function (bar) {
	        return {
	            text: bar.text,
	            iconCls: "icon-" + bar.icon,
	            handler: bar.click,
	            disabled: bar.disabled,
	            toggle: bar.toggle
	        };
	    },
	    // 列转换
	    _2column: function (col) {
	        return {
	            title: col.display, //列标题
	            field: col.name, 	//列字段
	            width: col.minWidth || col.width, //列宽
	            rowspan: col.rowspan, //表明一个单元格跨几行
	            colspan: col.colspan, //表明一个单元格跨几列
	            align: col.align, 	//表明如何对其列数据，可选值：'left'，'right'，'center'
	            sortable: (col.sort != null), //设置为true允许对该列排序
	            resizable: col.resizable, 	//设置为true允许该列被缩放
	            hidden: col.hidden, 			//设置为true将隐藏列
	            childColumns: col.childColumns, //子列
	            formatter: col.render			//格式化单元格函数，有3个参数：value：字段的值。rowData：行数据。rowIndex：行索引。
	        };
	    }
	}
	// 表格定义
	g.grid.target.datagrid(gridOpt.convert(g));
	//分页处理
	var pg = g.grid.target.datagrid("getPager");
	if (pg && pg.length > 0) {
		$(pg).pagination({
			pageSize: gd.pageSize || 15,//每页显示的记录条数，默认为10  
			pageList: gd.pageList || [10,15,20,25,30],//可以设置每页记录条数的列表  
			beforePageText: '', //页数文本框前显示的汉字  
			afterPageText: '/{pages}',
			displayMsg: ' <span id="' + g.grid.id + 'pinfo" style="padding-right:20px;"></span> show {from} - {to} lines    total {total} record',
			onRefresh: function (pageNumber, pageSize) {g.grid.LoadRemoteData(pageNumber, pageSize);},
			onChangePageSize: function () {var _option = g.grid.target.datagrid('options');g.grid.LoadRemoteData(_option.pageNumber, _option.pageSize);},
			onSelectPage: function (pageNumber, pageSize) {g.grid.LoadRemoteData(pageNumber, pageSize);}
		});
	}
	
	if(g.form) {
		//放在此处是因为之前的还没有生成表格，所以没办法把#formid加入到toolbar里面
		//var flag = g.form.getDisplayType();
		//if(flag == '3') {
			//g.form.target.hide();
			g.grid.target.datagrid('toolbarAddSearch',g.form.id);
		//}
	}
}

function formRender(g) {
	var gf = g.formDefine;
	var id = g.formDefineId || gf.formDefineId || 'formid';
	if(gf.newline != false) gf.newline = true;
	gf.inputWidth = gf.inputWidth || 100;
	gf.labelWidth = gf.labelWidth || 78;
	var formOpt = {
	    init: function () {
	        var that = this;
	        var fields = gf.fields;

	        // form列的对象
	        that.obj = {};
	        // form列从服务器取数据的对象
	        that.serverObj = {};
	        // 显示列的数量
	        that.fieldLength = 0;

	        that.html = [];
	        var matchtag = false;
	        for (var i = 0; i < fields.length; i++) {
	            var field = fields[i];
	            if (!field.inputWidth) field.inputWidth = gf.inputWidth;
	            var arr = field.name.split('-');
	            for (var n = 0; n < arr.length; n++) { 
	                that.obj[arr[n]] = $.extend({}, field, { name: arr[n], isinterval: arr.length > 1, index: n });
	                if (field.type != 'hidden') that.fieldLength++;
	            }
	            if (field.serviceDataName) that.serverObj[field.serviceDataName] = field;
	            if (field.data) that.serverObj[field.data] = field;

	            // html处理
	            if (gf.newline && field.newline) {
	                if (matchtag) that.html.push('</div>');
	                that.html.push('<div class="formatrow" ');
	                if (field.nlstyle) that.html.push(' style="' + field.nlstyle + '"');
	                that.html.push('>');
	                matchtag = true;
	            }
	            that.fieldHtml(field);
	        }
	    },
	    Html: function () {
	        //生成html
	        $("#" + id).append(this.html.join(''));
	        // 绑定事件
	        //fromEvent(gf,fd);
	        $.parser.parse("#" + id);
	    },
	    _widthHtml: function (width) {
	        if (width) this.html.push(' style="width:' + width + 'px"');
	    },
	    _dataoptions: function (field) {
	        that = this;
	        if (field.dataoptions) { that.html.push(' data-options="' + field.dataoptions + '"'); }
	    },
	    fieldHtml: function (field) {
	        var that = this;
	        var arr = [];
	        // label
	        var _id = id + field.name;
	        var inputwidth = field.inputWidth || gf.inputWidth || 100;
	        var lablewidth = field.labelWidth || gf.labelWidth || 78;

	        if (field.type == 'button') {
	            that.html.push('<span id="lbl_' + _id + '" class="span-button" ');
	            that._widthHtml(inputwidth);
	            that.html.push('><a href="#"  id="' + _id + '" class="easyui-linkbutton" >' + field.display + '</a>');
	            that.html.push('</span>');
	        } else if (field.type == 'hidden') {
	            that.html.push('<input type="hidden" id="' + _id + '">');
	        } else {
	            that.html.push('<span id="lbl_' + _id + '"  class="span-label" ');
	            if (!field.display || field.display == "" || field.labelWidth == 0) lablewidth = 5;
	            that._widthHtml(lablewidth);
	            if (field.labelWidth == 0) that.html.push('></span>');
	            else that.html.push('>' + field.display + '</span>');
	            if (field.tip) {
	                that.html.push('<span id="input_' + _id + '" class="span-input easyui-tooltip" title="' + field.tip + '"');
	            } else {
	                that.html.push('<span id="input_' + _id + '" class="span-input" ');
	            }

	            // 处理间隔
	            var arrname = field.name.split('-');
	            that._widthHtml(arrname.length > 1 ? (inputwidth * arrname.length + 20) : inputwidth);
	            that.html.push('>');

	            for (var i = 0; i < arrname.length; i++) {
	                _id = id + arrname[i];
	                switch (field.type) {
	                    case 'text':
	                        if (field.validate == 'number') {
	                            that.html.push('<input class="easyui-numberbox" type="text" id="' + _id + '"');
	                        } else {
	                            that.html.push('<input class="easyui-validatebox" type="text" id="' + _id + '"');
	                        }
	                        that._widthHtml(inputwidth - 6); //减6是因为input会有border：2，padding：1的间隔
	                        that.html.push('></input>');
	                        break;
	                    case 'password':
	                        that.html.push('<input class="easyui-validatebox" value="" type="password" id="' + _id + '"');
	                        that.html.push('></input>');
	                        break;
	                    case 'template':
	                        that.html.push('<span id="' + _id + '">');
	                        if (field.render) that.html.push(field.render());
	                        that.html.push('</span>');
	                        break;
	                    case 'select':
	                        that.html.push('<select class="easyui-combobox" id="' + _id + '" data-options="panelHeight:\'auto\',editable:false ');
	                        if (field.multiple) { that.html.push(' ,multiple:true '); }
	                        //that._dataoptions(field);
	                        if (field.data) {
	                            that.html.push(' ,valueField:\'value\',textField:\'text\',data:DataDict[\'' + field.data + '\']');
	                        }
	                        that.html.push('" ');
	                        that._widthHtml(inputwidth);
	                        that.html.push('></select>');
	                        break;
	                    case 'selecttree':
	                        that.html.push('<select class="easyui-combotree" multiple id="' + _id + '" ');
	                        that._dataoptions(field);
	                        that._widthHtml(inputwidth);
	                        that.html.push('></select>');
	                        break;
	                    case 'date':
	                        that.html.push('<input class="easyui-datebox"  type="text" id="' + _id + '" ');
	                        that._dataoptions(field);
	                        that._widthHtml(inputwidth);
	                        that.html.push('></input>');
	                        break;
	                    case 'datetime':
	                        that.html.push('<input class="easyui-datetimebox" type="text" id="' + _id + '" ');
	                        that._dataoptions(field);
	                        that._widthHtml(inputwidth);
	                        that.html.push('></input>');
	                        break;
	                    case 'textarea':
	                        that.html.push('<textarea id="' + _id + '"  name="' + _id + '" ');
	                        that._dataoptions(field);
	                        that._widthHtml(inputwidth - 6);
	                        that.html.push(' rows="' + (field.rows || 5) + '" ');
	                        that.html.push('></textarea>');
	                        break;

	                }
	                if (i != arrname.length - 1) that.html.push('-');
	            }
	            that.html.push('</span>');
	        }
	    },
	    bindEvent: function (form) {
	        var that = this;
	        $.each(that.obj, function (name, field) {
	            var _id = "#" + id + field.name;
	            // 点击事件处理
	            if (field.click) {
	                if (typeof (field.click) == "string") {
	                    $(_id).bind("click", function () {
	                        if (window[cfield.click]) { window[cfield.click](); }
	                    })
	                } else if (typeof (field.click) == "function") {
	                    $(_id).bind("click", field.click);
	                }
	            }
	            //change事件
	            else if (field.onSelected) {
	                (function () {
	                    var _onselected;
	                    if (typeof (field.onSelected) == "string")
	                        _onselected = window[field.onSelected];
	                    else if (typeof (field.onSelected) == "function")
	                        _onselected = field.onSelected;
	                    $(_id).combobox({ onSelect: function () { _onselected(field.name, form); } });
	                })();
	            }

	            // url参数绑定
	            var p = $.getPara(field.name);
	            if (p && field.type == 'date') {
	                var d = new Date(); // 获取今天时间
	                d.setMonth(d.getMonth() + 1 + parseInt(p)); //加一个月，同理，可以加一天：getDate()+1，加一年：getYear()+1
	                p = d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate();
	            }
	            if (p) form.setItemValue(field.name, p);
	        });
	    },
	    onLoaded: function (form, data) {
	        // 绑定事件
	        this.bindEvent(form);
	        // 对field进行处理
	        if (gf.fieldsInit) gf.fieldsInit(form);
	        // 加载onload
	        if (gf.onLoaded) gf.onLoaded(data, form);
	        // 
	        if (g.autosearch) g.autosearch();
	        else form.target.show();
	    },
	    getRemoteFields: function () {
	        var that = this;
	        var arr = [];
	        $.each(that.serverObj, function (name, field) {
	            arr.push(name);
	        });
	        return arr.join();
	    }
	};
	// 转换formDefine为需要的格式和html
	formOpt.init();
	// 把生成的html更改为easyui
	formOpt.Html();
	
	// 提供g.form供外部访问
	g.form = {
	    // 表格id
	    id: id,
	    // 对象
	    target: $('#' + id),
	    getItemValue: function (name) {
	        var t = formOpt.obj[name];
	        if (!t) return "";
	        var id = '#' + this.id + name;
	        switch (t.type) {
	            case 'text':
	            case 'textarea':
	            case 'hidden':
	                return $(id).val();
	            case 'template':
	                return $(id).html();
	            case 'select':
	                if (!t.multiple)
	                    return $(id).combobox('getValue');
	                else
	                    return $(id).combobox('getValues').join(',');
	            case 'selecttree':
	                return $(id).combotree('getValue');
	            case 'date':
	                if (t.dateFormat && t.dateFormat != "")
	                    return $.fn.datebox.defaults.parser($(id).datebox('getValue')).Format(t.dateFormat);
	                return $(id).datebox('getValue').replace(/-/g, '');
	            case 'datetime':
	                return $(id).datetimebox('getValue').replace(/-/g, '');
	        }
	        return null;
	    },
	    getItemText: function (name) {
	        var t = formOpt.obj[name];
	        if (!t) return "";
	        var id = '#' + this.id + name;
	        switch (t.type) {
	            case 'text':
	            case 'password':
	            case 'textarea':
	            case 'hidden':
	                return $(id).val();
	            case 'template':
	                return $(id).html();
	            case 'select':
	                return $(id).combobox('getText');
	            case 'selecttree':
	                return $(id).combotree('getText');
	            case 'date':
	                return $(id).datebox('getValue');
	            case 'datetime':
	                return $(id).datetimebox('getValue');
	        }
	        return null;
	    },
	    getParams: function () {
	        var that = this;
	        var obj = {};
	        $.each(formOpt.obj, function (name, field) {
	            if (!field.noJson && field.type != "button") {
	                var v = that.getItemValue(name);
	                if (v && v != "")
	                    obj[name] = v;
	            }
	        });
	        return obj;
	    },
	    getDisplayType: function () {
	        if (gf.displayType && gf.displayType != "") return gf.displayType
	        if (formOpt.fieldLength < 6) {
	            return 3;
	        }
	        return 2;
	    },
	    getParamsStr: function () {
	        var that = this;
	        var arr = [];
	        var sp = ":";
	        $.each(formOpt.obj, function (name, field) {
	            if (field.type != "textarea" && field.type != "hidden" && !field.noJson) {
	                var k = that.getItemValue(name);
	                if (k && k != "") {
	                    var str = that.getItemText(name);
	                    if (str) {
	                        if (field.isinterval && field.index == 0) sp = ">=";
	                        else if (field.isinterval && field.index > 0) sp = "<=";
	                        else sp = ":";
	                        arr.push(field.display + "<span>" + sp + str + "</span>");
	                    }
	                }
	            }
	        });
	        if (gf.getParamsStr) {
	            arr = gf.getParamsStr(that, arr);
	        }
	        return '<span style="line-height:20px;">'+arr.join(' , ')+'</span>';
	    },
	    setItemValue: function (name, value) {
	        var field = formOpt.obj[name];
	        var id = '#' + this.id + name;
	        switch (field.type) {
	            case 'text':
	            case 'password':
	            case 'textarea':
	            case 'hidden':
	                $(id).val(value);
	                break;
	            case 'template':
	                $(id).html(value);
	                break;
	            case 'select':
	                var _oldValue = $(id).combobox('getValue');
	                var _data = $(id).combobox('getData');
	                var _opt = $(id).combobox('options');
	                for (var i = 0; i < _data.length; i++) {
	                    if (value == _data[i][_opt.valueField]) {
	                        $(id).combobox('setValue', value);
	                        if (field.onSelected && value != _oldValue) field.onSelected(field.name, this);
	                        break;
	                    }
	                }
	                break;
	            case 'selecttree':
	                $(id).combotree('setValue', value);
	                break;
	            case 'date':
	                if (value == "") $(id).datebox('setValue', '');
	                else $(id).datebox('setValue', $.fn.datebox.defaults.formatter($.fn.datebox.defaults.parser(value)));
	                break;
	            case 'datetime':
	                $(id).datetimebox('setValue', value);
	                break;
	        }
	    },
	    // 重置查询条件，除了hidden和select的optionType不为1和2的
	    resetItemValue: function () {
	        var that = this;
	        $.each(formOpt.obj, function (name, field) {
	            if (field.type != "button" && field.type != "hidden") {
	                if (field.type == "select") {
	                    if (!field.optionType || field.optionType != "3") {
	                        var id = '#' + that.id + field.name;
	                        $(id).combobox("clear");
	                    }
	                } else {
	                    that.setItemValue(field.name, "");
	                }
	            }
	        });
	    },
	    _abled: function (name, b) {
	        var field = formOpt.obj[name];
	        var id = '#' + this.id + name;
	        if (field.type == 'button') {
	            $(id).linkbutton(b ? 'disable' : 'enable');
	        } else if (field.type == 'text') {
	            $(id).disabled = b;
	        } else if (field.type == 'select') {
	            $(id).combo(b ? 'disable' : 'enable');
	        }
	    },
	    disableItem: function (name) {
	        this._abled(name, true);
	    },
	    enableItem: function (name) {
	        this._abled(name, false);
	    },
	    _visible: function (name, b) {
	        var field = formOpt.obj[name];
	        var lblid = '#lbl_' + this.id + name;
	        var inputid = '#input_' + this.id + name;
	        if (field.type == 'button') {
	            $(lblid)[b ? "show" : "hide"]();
	        } else {
	            $(lblid)[b ? "show" : "hide"]();
	            $(inputid)[b ? "show" : "hide"]();
	        }
	    },
	    showItem: function (name) {
	        this._visible(name, true);
	    },
	    hideItem: function (name) {
	        this._visible(name, false);
	    },
	    setFocusItem: function (name) {
	        $('#' + this.id + name).focus();
	    },
	    _binddata: function (dataobj, optionType) {
	        dataobj = $.extend({ textField: 'Value', valueField: 'Key' }, dataobj);
	        var o = {};
	        o[dataobj.textField] = '全部';
	        o[dataobj.valueField] = '';
	        o['selected'] = true;

	        var arr = [];
	        if (!optionType || optionType && optionType == 2) {
	            arr.push(o);
	            dataobj.data = arr.concat(dataobj.data);
	        }
	        else if (optionType && optionType == 1) {
	            o[dataobj.textField] = '请选择';
	            arr.push(o);
	            dataobj.data = arr.concat(dataobj.data);
	        }
	        else if (optionType && optionType == 4) { }
	        else {
	            if (dataobj.data.length > 0) {
	                dataobj.data[0]["selected"] = true;
	            }
	        }
	        return dataobj;
	    },
	    _getlength: function (str) {
	        return str.toString().replace(/[^\x00-\xff]/g, "aa").length;
	    },
	    _comboPanelfix: function (dataobj, inputWidth) {
	        var that = this;
	        if (dataobj.data.length > 10)
	            dataobj.panelHeight = '200';
	        var nmax = 0, str, l;
	        for (var i = 0; i < dataobj.data.length; i++) {
	            s = dataobj.data[i][dataobj.textField];
	            l = that._getlength(s);
	            if (l > nmax) nmax = l;
	        }
	        nmax = nmax * 7.2;
	        if (nmax > inputWidth) dataobj.panelWidth = nmax;
	    },
	    bind: function (name, dataobj, optionType) {
	        var field = formOpt.obj[name];
	        var id = '#' + this.id + name;
	        if (field && field.type == 'select') {
	            dataobj = dataobj || $.extend($(id).combobox('options'), { data: $(id).combobox('getData') });
	            dataobj = this._binddata(dataobj, optionType);
	            this._comboPanelfix(dataobj, field.inputWidth);
	            $(id).combobox(dataobj);
	        } else if (field.type == 'selecttree') {
	            dataobj = this._binddata(dataobj, optionType);
	            this._comboPanelfix(dataobj, field.inputWidth);
	            $(id).combotree(dataobj);
	        }
	        if (field.onSelected) field.onSelected(field.name, this);
	    },
	    getItemServiceData: function (name) {
	        return formOpt.serverObj[name].serviceData;
	    },
	    loadRemoteData: function () {
	        var that = this;
	        if (!(gf.url || gf.urlType)) { formOpt.onLoaded(that, null); return; }
	        var params = "";
	        if (gf.params) {
	            if (typeof gf.params == 'function')
	                params = gf.params();
	            else
	                params = gf.params;
	        }
	        // 新版查询条件
	        if (gf.urlType == 'GetCond') {
	            params = $.toJSON({ fields: formOpt.getRemoteFields(), outId: $.getPara('outid') });
	        } else if (gf.urlType == 'JunhongAjaxInitCond') {
	            params = "{Params:["
	            $.each(formOpt.serverObj, function (name, field) {
	                params += "'" + name + "',";
	            });
	            params += "]}";
	        }
	        var ajaxObj = {
	            urlType: gf.urlType,
	            url: gf.url,
	            model: params,
	            success: function (data) {
	                // 新版查询条件   	
//	                if (gf.urlType == 'GetCond') {
//	                    for (var p in data) {
//	                        var field = formOpt.serverObj[p];
//	                        var d = data[p];
//	                        if (field && field.type == 'select') {
//	                            var _o = { data: d, valueField: 'Key', textField: 'Value', panelHeight: 'auto', panelWidth: 'auto' };
//	                            field.serviceData = d;
//	                            that.bind(field.name, _o, field.optionType);
//	                        }
//	                    }
//	                } else 
                    if (data instanceof Array) {
	                    $(data).each(function (index, serField) {
	                        var field = formOpt.serverObj[serField.name];
	                        if (field && field.type == 'select') {
	                            var _o = { data: serField.items, valueField: 'itemId', textField: 'itemName', panelHeight: 'auto', listWidth: 500 };
	                            field.serviceData = serField.items;
	                            that.bind(field.name, _o, field.optionType);
	                        }
	                    });
	                } else {
	                    if (data.Options) {
	                        $.each(formOpt.serverObj, function (name, field) {
	                            if (field.serviceDataName) {
	                                if (data.Options[field.serviceDataName]) {
	                                    field.serviceData = data.Options[field.serviceDataName];
	                                    var _o = { data: field.serviceData, valueField: 'itemId', textField: 'itemName' };

	                                    that.bind(field.name, _o, field.optionType);
	                                }
	                                if (data.DefaultValues[field.serviceDataName]) {
	                                    that.setItemValue(field.name, data.DefaultValues[field.serviceDataName]);
	                                }
	                            }
	                        });
	                    } else {
	                        for (var p in data) {
	                            var field = formOpt.serverObj[p];
	                            if (field) {
	                                var d = data[p];
	                                if (d) {
	                                    that.setItemValue(field.name, d);
	                                }
	                            }
	                        }
	                    }
	                }
	                formOpt.onLoaded(that, data);
	            },
	            failure: function (msg) {

	            }
	        }
	        $.ajaxHandler(ajaxObj);
	    }
	}
	
	// 表单则有提交方法
	function submit(g) {
		var f = g.form;
		var gf = g.formDefine;
        var params = f.getParams();
		if (gf.submitParams) {
            params = gf.submitParams(params);
        }
        if (gf.submitCheck) {
            var checkObj = gf.submitCheck(params,g.form);
            if (checkObj && checkObj != "") {
                $.alert(checkObj);
                return false;
            }
        }
		
		var ajaxObj = {
			urlType:gf.submitUrlType,
			url:gf.submitUrl,
			model:$.toJSON(params),
			success:function(data) {
				if (gf.submitSuccess)
                    gf.submitSuccess(data);
			},
			failure:function(msg) {
				if (gf.submitError)
                    gf.submitError(msg);
			}
		}
		$.ajaxHandler(ajaxObj);
    }
	if(gf.submitUrl && gf.submitUrl != ""){
		g.form.submit = function(){
			submit(g);
		}
	}
	
	// 获取数据
	g.form.loadRemoteData();
}

// 扩展easyui datagrid的两个方法.对按钮进行enable,disable控制
$.extend($.fn.datagrid.methods, {
	setTitle:function(jq,param) {
		return jq.each(function(){
			var title = $(this).parent().parent().prev().children("div.panel-title");
			if(title) {
				if(typeof param == 'string') {
					$(title).html(param);
				} else {
					$(title).html(param.title);
					if(param.click){
						title.unbind().bind("click", param.click).addClass('cursor');
						$.tip('点击这里显示或关闭查询条件');
					}
				}
			}
		});
	},
	toolbarAddSearch:function(jq,id) {
		return jq.each(function(){
			var toolbar = $(this).parent().prev("div.datagrid-toolbar");
			var tr=toolbar.find("tr");
			var td=$("<td></td>").appendTo(tr);
			$('#'+id).appendTo(td);
			td = null;
			tr = null;
			toolbar = null;
			return false;
		});
	},
	toolbarDisabled:function(jq,param){
		return jq.each(function(){
			var items = $(this).parent().prev("div.datagrid-toolbar").find("a");
			var text = null;
			items.each(function(){				
				text = $(this).data().linkbutton.options.text;
				if(text == param){
					$(this).linkbutton('disable');
					text = null;
					return false;
				}
			});
		});
	},
	toolbarEnabled:function(jq,param){
		return jq.each(function(){
			var items = $(this).parent().prev("div.datagrid-toolbar").find("a");
			var text = null;
			items.each(function(){				
				text = $(this).data().linkbutton.options.text;
				if(text == param){
					$(this).linkbutton('enable');
					text = null;
					return false;
				}
			});
		});
	}           
});
$.extend($.fn.datebox.defaults, {
    parser: function (s) {
        if (s) {
            var a = s.split('-');
            var d = new Date(parseInt(a[0],10), parseInt(a[1],10) - 1, parseInt(a[2],10));
            return d;
        } else {
            return new Date();
        }
    }
});
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

// 日期控件默认格式
$.fn.datebox.defaults.width = 100;
$.fn.calendar.defaults.weeks = ['日', '一', '二', '三', '四', '五', '六'];
$.fn.calendar.defaults.months = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"];
$.fn.datebox.defaults.formatter = function (date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    if (m < 10) m = '0' + String(m);
    if (d < 10) d = '0' + String(d);
    return y + '-' + m + '-' + d;
};

$.fn.datebox.defaults.parser = function (s) {
    var t = Date.parse(s);
    if (!isNaN(t)) {
        return new Date(t);
    } else {
        return new Date();
    }
}
